package com.gujia.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.gujia.async.EventModel;
import com.gujia.async.EventProducer;
import com.gujia.async.EventType;
import com.gujia.service.UserService;
import com.sun.deploy.net.HttpResponse;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Created by GuJia on 2017/6/20.
 */
@Controller
public class LoginController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    UserService userService;

    @Autowired
    private EventProducer eventProducer;


    /**
     * 注册
     * @param model
     * @param name
     * @param password
     * @return
     */
    @RequestMapping(path={"/reg/"},method = {RequestMethod.POST,RequestMethod.GET})
    //@ResponseBody
    public String register(Model model, @RequestParam("username") String name,
                           @RequestParam("password") String password,
                           HttpServletResponse response){
       // System.out.println("===="+name);
        Map<String,String> map = userService.register(name,password);

       try{
           if(!map.containsKey("ticket")){
               model.addAttribute(map.get("msg"));
               return "login";
           }else{
               Cookie cookie = new Cookie("ticket",map.get("ticket"));
               cookie.setPath("/");
               response.addCookie(cookie);
           }

           return "redirect:/";
       }catch(Exception ex){

           logger.error("Register Error:"+ex.getMessage());
           return "login";
       }

        //return "login";
    }


    @RequestMapping(path={"/reglogin"},method = {RequestMethod.POST,RequestMethod.GET})
    //@ResponseBody
    public String registerLogin(Model model, @RequestParam(value = "next", required = false) String next){

        model.addAttribute("next", next);
        return "login";
    }

    @RequestMapping(path={"/login/"},method = {RequestMethod.POST,RequestMethod.GET})
    //@ResponseBody
    public String login(Model model, @RequestParam("username") String name,
                        @RequestParam("password") String password,
                        @RequestParam(value="next", required = false) String next,
                        @RequestParam(value = "rememberme",defaultValue = "false") boolean rememberme,
                        HttpServletResponse response){



        try{
            Map<String,Object> map = userService.login(name,password);
            if(!map.containsKey("ticket")){
                model.addAttribute("msg",map.get("msg"));
                return "login";
            }else{
                Cookie cookie = new Cookie("ticket",(String)map.get("ticket"));
                cookie.setPath("/");
                response.addCookie(cookie);
                eventProducer.fireEvent(new EventModel(EventType.LOGIN)
                        .setExt("username", name).setExt("email", "gj19890227@qq.com")
                        .setActorId((int)map.get("userId")));
            }

            if (StringUtils.isNotBlank(next)) {
                return "redirect:" + next;
            }

            return "redirect:/";
        }catch(Exception ex){

            logger.error("Register Error:"+ex.getMessage());
            return "login";
        }

        //return "login";
    }

    @RequestMapping(path={"/logout"},method = {RequestMethod.GET,RequestMethod.POST})
    public String logout(@CookieValue("ticket") String ticket){
        userService.logout(ticket);
        return "redirect:/";
    }

}
